package com.manager.devicemanager.controller;

import com.manager.devicemanager.common.DataSourceNameEnum;
import com.manager.devicemanager.common.ICComponentPriority;
import com.manager.devicemanager.common.Result;
import com.manager.devicemanager.entity.ComponentStatus;
import com.manager.devicemanager.service.IComponentStatusService;
import com.manager.devicemanager.util.StringDealUtils;
import com.manager.devicemanager.vo.ComponentStatusRequestVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wpf
 * @since 2025-06-09
 * @description 集成器件状态
 */
@RestController
@RequestMapping("/componentStatus")
public class ComponentStatusController {
    @Autowired
    private IComponentStatusService iComponentStatusService;
    private static final List<String> PRIORITIES = Arrays.stream(ICComponentPriority.values())
            .map(ICComponentPriority::getDescription)
            .collect(Collectors.toList());
    private static final List<Integer> PRIORITIES1 = Arrays.stream(ICComponentPriority.values())
            .map(ICComponentPriority::getCode)
            .collect(Collectors.toList());
//    private static final List<String> PRIORITIES = Arrays.asList("闩锁", "BRAM翻转","CRAM翻转", "正常");
//    private static final List<Integer> PRIORITIES1 = Arrays.asList(6, 9, 10, 0);
    final static int ROW_LENGTH = 6;
    final static int GROUP_LENGTH = 8;

    // 封装合并字符串并去除引号的方法
    private static String mergeAndTrimQuotes(String str1, String str2) {

        String combined = str2 != null ? str1 +","+ str2 : str1;
        return combined != null ? StringDealUtils.dealIComponentString(combined) : null;
    }


    @RequestMapping("/getComponentStatus")
    public Result<String[][]> getComponentStatus(@RequestBody ComponentStatusRequestVO componentStatusRequestVO) {
        try {
            ComponentStatus lastData = iComponentStatusService.getLastData(DataSourceNameEnum.ICBOARDCONFIG.getDataSourceName()+componentStatusRequestVO.getDatasourceindex());
//            ComponentStatus lastData1 = iComponentStatusService.getLastData(DataSourceNameEnum.ICBOARDCONFIG.getDataSourceName() + "1");
            if (lastData == null) {
                lastData = new ComponentStatus();
            }
//            if (lastData1 == null) {
//                lastData1 = new ComponentStatus();
//            }

// 初始化存储合并后状态的数组
            String[] statuses = new String[12];
            // 提前提取 lastData 的属性到数组
            String[] lastDataStatuses = {lastData.getS1(), lastData.getS2(), lastData.getS3(), lastData.getS4(), lastData.getS5(), lastData.getS6(), lastData.getS7(), lastData.getS8(), lastData.getS9(), lastData.getS10(), lastData.getS11(), lastData.getS12()};
            // 提前提取 lastData1 的属性到数组
//            String[] lastData1Statuses = {lastData1.getS1(), lastData1.getS2(), lastData1.getS3(), lastData1.getS4(), lastData1.getS5(), lastData1.getS6(), lastData1.getS7(), lastData1.getS8(), lastData1.getS9(), lastData1.getS10(), lastData1.getS11(), lastData1.getS12()};
            // 初始化行列互换后的二维数组
            String[][] processedStatuses = new String[ROW_LENGTH][statuses.length];

            for (int i = 0; i < statuses.length; i++) {
                Integer[] rowResult = processStringICNew(lastDataStatuses[i]);
//                Integer[] rowResult1 = processStringICNew(lastData1Statuses[i]);
                for (int j = 0; j < ROW_LENGTH; j++) {
                    // 行列互换存储数据
                    Integer value1 = rowResult[j];
//                    Integer value2 = rowResult1[j];
//                    Integer higherPriorityValue = getHighestPriorityValueCode(new Integer[]{value1, value2});
                    int i1 = PRIORITIES1.indexOf(value1);
                    processedStatuses[j][i] = PRIORITIES.get(i1);
                }
            }

            return Result.success(processedStatuses);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    public static String[] processString(String input) {
        if (input == null) {
            return new String[ROW_LENGTH];
        }
        // 按 : 分割字符串
//        input = input.replaceAll("^\"|\"$", "");
        input= StringDealUtils.dealIComponentString(input);
        String[] values = input.split(",");
        if (values.length != ROW_LENGTH * GROUP_LENGTH) {
            throw new IllegalArgumentException("状态值必须包含 " + ROW_LENGTH * GROUP_LENGTH + " 个以 , 分隔的值");
        }
        String[] result = new String[ROW_LENGTH];
        for (int i = 0; i < ROW_LENGTH; i++) {
            int startIndex = i * GROUP_LENGTH;
            String[] group = Arrays.copyOfRange(values, startIndex, startIndex + GROUP_LENGTH);
            result[i] = getHighestPriorityValue(group);
        }
        return result;
    }

    public static Integer[] processStringICNew(String input) {
        if (input == null) {
            return new Integer[ROW_LENGTH];
        }

        Integer[] values = StringDealUtils.dealICComponentStringToArray(input);
        if (values.length != ROW_LENGTH * GROUP_LENGTH) {
            throw new IllegalArgumentException("状态值必须包含 " + ROW_LENGTH * GROUP_LENGTH + " 个以 , 分隔的值");
        }
        Integer[] result = new Integer[ROW_LENGTH];
        for (int i = 0; i < ROW_LENGTH; i++) {
            int startIndex = i * GROUP_LENGTH;
            Integer[] group = Arrays.copyOfRange(values, startIndex, startIndex + GROUP_LENGTH);
            result[i] = getHighestPriorityValueCode(group);
        }
        return result;
    }

    /**
     * 根据优先级获取数组中优先级最高的值
     *
     * @param group 包含 8 个值的数组
     * @return 优先级最高的值
     */
    private static String getHighestPriorityValue(String[] group) {
        int highestPriorityIndex = Integer.MAX_VALUE;
        for (String value : group) {
            int index = PRIORITIES.indexOf(value);
            if (index != -1 && index < highestPriorityIndex) {
                highestPriorityIndex = index;
            }
        }
        return highestPriorityIndex == Integer.MAX_VALUE ? null : PRIORITIES.get(highestPriorityIndex);
    }


    private static Integer getHighestPriorityValueCode(Integer[] group) {
        int highestPriorityIndex = Integer.MAX_VALUE;
        for (Integer value : group) {
            int index = PRIORITIES1.indexOf(value);
            if (index != -1 && index < highestPriorityIndex) {
                highestPriorityIndex = index;
            }
        }
        return highestPriorityIndex == Integer.MAX_VALUE ? null : PRIORITIES1.get(highestPriorityIndex);
    }

}
